package com.ruoyi.system.service.impl;

import java.util.List;

import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ExceptionUtil;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import com.ruoyi.common.utils.html.EscapeUtil;
import com.ruoyi.system.domain.SysRoom;
import com.ruoyi.system.mapper.SysRoomMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.SysStudentMapper;
import com.ruoyi.system.domain.SysStudent;
import com.ruoyi.system.service.ISysStudentService;
import com.ruoyi.common.core.text.Convert;

import javax.validation.ConstraintViolationException;
import javax.validation.Validator;

/**
 * 学员Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-01-06
 */
@Service
public class SysStudentServiceImpl implements ISysStudentService 
{
    private static final Logger log = LoggerFactory.getLogger(SysStudentServiceImpl.class);
    @Autowired
    private SysStudentMapper sysStudentMapper;

    @Autowired
    private SysRoomMapper sysRoomMapper;

    @Autowired
    protected Validator validator;

    /**
     * 查询学员
     * 
     * @param studentId 学员主键
     * @return 学员
     */
    @Override
    public SysStudent selectSysStudentByStudentId(Long studentId)
    {
        return sysStudentMapper.selectSysStudentByStudentId(studentId);
    }

    /**
     * 查询学员身份证号
     *
     * @param idcard 身份证号
     * @return 学员
     */
    public SysStudent selectSysStudentByIdcard(String idcard)
    {
        return sysStudentMapper.selectSysStudentByIdcard(idcard);
    }

    /**
     * 查询学员列表
     * 
     * @param sysStudent 学员
     * @return 学员
     */
    @DataScope(deptAlias = "s", userAlias = "u")
    @Override
    public List<SysStudent> selectSysStudentList(SysStudent sysStudent)
    {
        return sysStudentMapper.selectSysStudentList(sysStudent);
    }

    /**
     * 新增学员
     * 
     * @param sysStudent 学员
     * @return 结果
     */
    @Override
    public int insertSysStudent(SysStudent sysStudent)
    {
        sysStudent.setCreateTime(DateUtils.getNowDate());
        return sysStudentMapper.insertSysStudent(sysStudent);
    }

    /**
     * 修改学员
     * 
     * @param sysStudent 学员
     * @return 结果
     */
    @Override
    public int updateSysStudent(SysStudent sysStudent)
    {
        sysStudent.setUpdateTime(DateUtils.getNowDate());
        return sysStudentMapper.updateSysStudent(sysStudent);
    }

    /**
     * 批量删除学员
     * 
     * @param studentIds 需要删除的学员主键
     * @return 结果
     */
    @Override
    public int deleteSysStudentByStudentIds(String studentIds)
    {
        return sysStudentMapper.deleteSysStudentByStudentIds(Convert.toStrArray(studentIds));
    }

    /**
     * 删除学员信息
     * 
     * @param studentId 学员主键
     * @return 结果
     */
    @Override
    public int deleteSysStudentByStudentId(Long studentId)
    {
        return sysStudentMapper.deleteSysStudentByStudentId(studentId);
    }

    /**
     * 导入用户数据
     *
     * @param sysStudentList 用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    public String importSysStudent(List<SysStudent> sysStudentList, Boolean isUpdateSupport, String operName)
    {
        if (StringUtils.isNull(sysStudentList) || sysStudentList.size() == 0)
        {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (SysStudent student : sysStudentList)
        {
            try
            {
                // 验证是否存在这个用户
                SysStudent u = sysStudentMapper.selectSysStudentByIdcard(student.getIdcard());
                if (StringUtils.isNull(u))
                {
                    BeanValidators.validateWithException(validator, student);
                    Long user_id = ShiroUtils.getUserId();
                    SysRoom sysRoom = sysRoomMapper.selectSysRoomByUserId(user_id);
                    SysUser user = ShiroUtils.getSysUser();
                    student.setRoomId(sysRoom.getRoomId());
                    student.setUserId(user_id);
                    student.setDeptId(ShiroUtils.getSysUser().getDeptId());
                    sysStudentMapper.insertSysStudent(student);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、学员 " + student.getStudentName() + " 导入成功");
                }
                else if (isUpdateSupport)
                {
                    BeanValidators.validateWithException(validator, student);
                    Long user_id = ShiroUtils.getUserId();
                    SysRoom sysRoom = sysRoomMapper.selectSysRoomByUserId(user_id);
                    SysUser user = ShiroUtils.getSysUser();
                    student.setRoomId(sysRoom.getRoomId());
                    student.setUserId(user_id);
                    student.setDeptId(ShiroUtils.getSysUser().getDeptId());

                    sysStudentMapper.updateSysStudent(student);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、学员 " + student.getStudentName() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、学员 " + student.getStudentName() + " 身份证号" + student.getIdcard() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String loginName = student.getStudentName();
                if (ExceptionUtil.isCausedBy(e, ConstraintViolationException.class))
                {
                    loginName = EscapeUtil.clean(loginName);
                }
                String msg = "<br/>" + failureNum + "、学员 " + loginName + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
